/**
 * 查询栏
 *
 * queryList[
 *      title： 标题（字符串）
 *      key： 唯一标识（字符串）
 *      url：数据加载的URL（字符串）
 *      forSort：默认显示的值的数量（输入数值）
 *      filter：是否需要查询过滤，必须配合forSort同时使用（true/false，默认为true）
 *      savePreference : 保存用户习惯，需要必须配合forSort同时使用（true/false，默认为false）
 * ]
 *
 */
var SearchBar = function(opt) {
    this.params = {
        containerId: "",
        queryList: [],
        textPlaceholder: "查询条件...",
        getQueryParamsFunc: null, // 获取参数字符串
        queryFunc: null, // 查询的方法
        afterRenderFunc: null,
        appendHtml: null
    };
    this.inited = false; // 是否已初始化
    this.cacheDatas = []; // 缓存数据

    this.init(opt);
};

SearchBar.prototype = {

    init: function(opt) {
        this.copyPropertyVal(opt, this.params);
    },

    render: function() {
        this.params.showLine = this.params.queryList.length > 0;

        var _this = this;
        include.includeFileToContainer("/public/tpl/searchBar.tpl", this.params.containerId, this.params, function() {
            if (_this.params.appendHtml != null) {
                var _html = _this.params.appendHtml();
                $("#appendDiv_" + _this.params.containerId).html(_html);
            }

            _this.bindEvent();
            // _this.setValue();
            _this.load();
        });
    },

    /**
     * 加载数据
     */
    load: function() {
        var _this = this;
        for (var i = 0; i < this.params.queryList.length; i++) {
            var _select = this.params.queryList[i];
            if (_select.data != null) {
                this.afterLoad(_select.data);
                continue;
            }

            var _url = _select.url;
            $.ajax({
                url: _url,
                cache: false,
                dataType: "json",
                type: "get",
                data: "select_url=" + encodeURIComponent(window.location.hash.replace("#", "")),
                success: function(data) {
                    _this.afterLoad(data);
                }
            });
        }
    },

    afterLoad: function(data) {
        this.cacheDatas.push(data);

        var html = '<li class="active" role-id="' + data.key + '" role-val="">全部</li>';
        for (var i = 0; i < data.datas.length; i++) {
            var d = data.datas[i];

            var _forSort = $("#ul_" + data.key).attr("role-forSort");
            _forSort = (_forSort != null ? parseInt(_forSort) : null);
            if (_forSort != null && i >= _forSort) {
                html += '<li role="more" role-more-val="1" class="li_more">查看更多...</li>';
                break;
            } else {
                html += '<li role-id="' + data.key + '" role-val="' + d.code + '">' + d.name + '</li>';
            }
        }
        $("#ul_" + data.key).html(html);

        this.bindLiEvent(data.key);

        if (!this.inited) {
            this.inited = true;
            if (this.params.afterRenderFunc != null) this.params.afterRenderFunc();
        }
    },

    /**
     * 打开或关闭更多
     */
    openOrCloseMore: function(key, openOrClose) {
        var _select = null;

        // 从缓存获取数据
        for (var i = 0; i < this.cacheDatas.length; i++) {
            if (this.cacheDatas[i].key == key) {
                _select = this.cacheDatas[i];
                break;
            }
        }
        if (_select == null) return;

        var _forSort = this.getQueryObj(key).forSort;
        var _filter = this.getQueryObj(key).filter;
        var html = '';
        if (openOrClose == 1) {
            // 移除“显示更多”并显示剩余的元素
            $("#ul_" + key).children().last().remove();
            for (var i = _forSort; i < _select.datas.length; i++) {
                html += '<li role-id="' + key + '" role-val="' + _select.datas[i].code + '">' + _select.datas[i].name + '</li>';
            }

            if (_filter == null || _filter == true) { html += '<input role="filter" type="text" class="li_input_filter" placeHolder="过滤条件" />'; }
            html += '<li role="closeMore" class="li_more">关闭更多</li>';
            $("#ul_" + key).append(html);

            $("#ul_" + key).find("input[role='filter']").focus();
        } else {
            $("#ul_" + key).find("input[role='filter']").val("");
            $("#ul_" + key).find("input[role='filter']").keyup();

            // 移除需要隐藏的元素
            $("#ul_" + key).children().each(function(i) {
                if (i > _forSort) $(this).remove();
            });
            html += '<li role="more" class="li_more">显示更多...</li>';
            $("#ul_" + key).append(html);

            // 判断当前ul是否有选中的值
            var _hasActive = false;
            $("#ul_" + key).children().each(function(i) {
                if ($(this).hasClass("active")) _hasActive = true;
            })
            if (!_hasActive) {
                $("#ul_" + key).children().first().addClass("active");
                this.query();
            }
        }
    },

    bindLiEvent: function(key) {
        var _this = this;

        $("#ul_" + key).delegate("li", "click", function() {
            var role = $(this).attr("role");
            if (role == "more") {
                // 显示全部
                _this.openOrCloseMore(key, 1);
            } else if (role == "closeMore") {
                // 关闭显示全部
                _this.openOrCloseMore(key, 0);
            } else {
                $("#ul_" + key).find("li[role-id='" + key + "']").removeClass("active");
                $(this).addClass("active");
                _this.query();

                // 产生气泡效果
                //$.tipsBox({ obj: $(this), str: "+" + (window.clickCount++) });

                // 检查是否需要保存用户习惯
                var _forSort = $("#ul_" + key).attr("role-forSort");
                var _savePreference = $("#ul_" + key).attr("role-savePreference");
                if ($(this).attr("role-val") != "" && _forSort != null && _forSort != "" && _savePreference == "true") {
                    $.ajax({
                        url: "select!saveUserPreference.action",
                        dataType: "json",
                        type: "post",
                        data: "userp.select_url=" + window.location.hash.replace("#", "") + "&userp.select_roleid=" + key + "&userp.select_val=" + $(this).attr("role-val"),
                        success: function(data) {

                        }
                    });
                }
            }
        });

        // 过滤查询事件
        $("#ul_" + key).delegate("input", "keyup", function() {
            if ($(this).attr("role") !== "filter") return;

            var _val = $(this).val();
            for (var i = 0; i < _this.cacheDatas.length; i++) {
                if (_this.cacheDatas[i].key != key) continue;

                for (var j = 0; j < _this.cacheDatas[i].datas.length; j++) {
                    var _data = _this.cacheDatas[i].datas[j];
                    var _name = _data.name || _data.NAME;
                    var _keyword1 = _data.keyword1 || _data.KEYWORD1 || "";
                    var _keyword2 = _data.keyword2 || _data.KEYWORD2 || "";

                    if (_val != "" && (_name.indexOf(_val) != -1 || _keyword1.indexOf(_val) != -1 || _keyword2.indexOf(_val) != -1)) {
                        $("#ul_" + key).find("li[role-val='" + _data.code + "']").addClass("li_filtered");
                    } else {
                        $("#ul_" + key).find("li[role-val='" + _data.code + "']").removeClass("li_filtered");
                    }
                }
            }
        });
    },

    bindEvent: function() {
        var _this = this;

        // 查询按钮点击事件
        $("#searchBtn_" + this.params.containerId).click(function() {
            _this.query();
            //$.tipsBox({ obj: $(this), str: "+" + (window.clickCount++) }); // 产生气泡效果
        });

        // 输入框回车事件
        $("#searchInput_" + this.params.containerId).keydown(function(e) {
            if (e.keyCode == 13) {
                _this.query();
                //$.tipsBox({ obj: $(this), str: "+" + (window.clickCount++) }); // 产生气泡效果
            }
        });
    },

    setValue: function(paramStr) {
        var paramObj = this.getRequest(paramStr);
        console.log(paramObj);

        if (paramObj.searchVal !== undefined && paramObj.searchVal !== '') {
            $('#searchInput_' + this.params.containerId).val(paramObj.searchVal);
        }
    },

    /**
     * 获取参数
     */
    getQueryParams: function() {
        if (this.params.getQueryParamsFunc != null) {
            return this.params.getQueryParamsFunc();
        }

        var params = "searchVal=" + ($("#searchInput_" + this.params.containerId).val() || "");
        for (var i = 0; i < this.params.queryList.length; i++) {
            var roleId = this.params.queryList[i].key;

            $("#ul_" + roleId).find("li[role-id='" + roleId + "']").each(function() {
                if ($(this).hasClass("active")) {
                    params += "&" + roleId + "=" + $(this).attr("role-val");
                }
            });
        }
        return params;
    },

    /**
     * 获取参数
     */
    getQueryValue: function(key) {
        if (key == "searchVal") {
            return ($("#searchInput_" + this.params.containerId).val() || "");
        }

        for (var i = 0; i < this.params.queryList.length; i++) {
            var roleId = this.params.queryList[i].key;
            if (roleId != key) continue;

            var val = "";
            $("#ul_" + roleId).find("li[role-id='" + roleId + "']").each(function() {
                if ($(this).hasClass("active")) {
                    val = $(this).attr("role-val");
                    return;
                }
            });
            if (val != "") return val;
        }
        return "";
    },

    query: function() {
        if (this.params.queryFunc != null) { this.params.queryFunc(this.getQueryParams()); }
    },

    getQueryObj: function(key) {
        for (var i = 0; i < this.params.queryList.length; i++) {
            if (this.params.queryList[i].key == key) return this.params.queryList[i];
        }
        return null;
    },

    copyPropertyVal: function(d, c) {
        for (var b in d) {
            for (var a in c) {
                if (b == a && d[b] != null) {
                    c[a] = d[b];
                    break
                }
            }
        }
    },

    getRequest: function(url) {
        if (url === undefined || url === null) {
            return {};
        }
        if (url.indexOf('?') === -1) {
            url = "?" + url;
        } 
        var theRequest = new Object(); 
        if (url.indexOf("?") != -1) {  
            var str = url.substr(1);  
            strs = str.split("&");  
            for (var i = 0; i < strs.length; i++) {   
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);  
            } 
        } 
        return theRequest;
    }
};